package com.topscomm.file.service;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.topscomm.file.FileInfoDTO;
import com.topscomm.file.FileProperties;
import com.topscomm.file.upload.FileUploadDispatcher;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;

import cn.hutool.core.io.FileUtil;

/**
 * 文件上传处理器
 * 
 * @description:
 * @author: donghang
 * @date: 2021年3月14日下午10:46:20
 * @modify:
 */
public class FileUploadFilter implements IFileProcessFilter {
	/**
	 * 上传，采用多线程上传
	 * 
	 * @description:
	 * @param paraMap
	 * @param dataProcessChain
	 * @return
	 * @author: donghang
	 * @date: 2021年3月18日下午11:58:25
	 * @modify:
	 */
	@Override
	public boolean doProcess(Map<String, Object> paraMap, IFileProcessChain dataProcessChain) throws Exception {
		// 组织FileInfoDTO，执行上传
		FileProperties fileProperties = (FileProperties) SpringUtil.getBean("fileProperties");
		String fileName = ConvertUtil.convertToString(paraMap.get("filename"));
		String identifier = ConvertUtil.convertToString(paraMap.get("identifier"));
		StringBuilder filePath = new StringBuilder();
		// 本地的目录
		String dirPath = filePath.append(fileProperties.getStorePath()).append("/").append(identifier).toString();
		// 将目录下所有非原始文件进行上传
		FileUploadDispatcher fileUploadDispatcher = (FileUploadDispatcher) SpringUtil.getBean("fileUploadDispatcher");
		List<File> listFiles = FileUtil.loopFiles(dirPath);
		for (File file : listFiles) {
			if (!file.getName().contains(fileName)) {
				// 并发上传到服务器
				FileInfoDTO fileInfo = new FileInfoDTO();
				fileInfo.setBucketName(ConvertUtil.convertToString(paraMap.get("bucketname")));
				String parentPath = file.getParentFile().getName();
				if (parentPath.equals(identifier)) {
					fileInfo.setFileDirPath(ConvertUtil.convertToString(paraMap.get("foldername")));
				} else {
					fileInfo.setFileDirPath(ConvertUtil.convertToString(paraMap.get("foldername")) + "/" + parentPath);
				}
				fileInfo.setFileName(file.getName());
				fileInfo.setLocateFilePath(file.getPath());
				fileInfo.setFileId(identifier);
				fileUploadDispatcher.handle(fileInfo);
			}
		}
		if (dataProcessChain != null) {
			dataProcessChain.doProcess(paraMap);
		}
		return true;
	}
}
